﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.DynamicProxy;
using DevFx.FrameWork.Attribute;

namespace DevFx.FrameWork.Trans
{
    /// <summary>
    /// 事务处理器
    /// </summary>
    internal class TransactionHelper
    {
        #region 变量

        private Transaction trans = new Transaction();

        #endregion

        #region 属性

        #endregion


        #region 事件
        /// <summary>
        /// 执行事务事件
        /// </summary>
        /// <param name="invocation">拦截器的信息</param>
        public void ExcuteWithTrans(IInvocation invocation)
        {
            //判断方法是否有开启事务支持的属性
            object[] transAttrs = invocation.Method.GetCustomAttributes(typeof(TransactionAttribute), false);
            if (transAttrs != null && transAttrs.Length > 0)
            {
                try
                {
                    trans.OpenDatabase();
                    trans.BeginTrans();
                    invocation.Proceed();
                    trans.CommitTrans();
                }
                catch
                {
                    trans.RollBack();
                    throw;
                }
            }
            else
            {
                invocation.Proceed();
            }
        }
        /// <summary>
        /// 执行非事务事件
        /// </summary>
        public void ExcuteWithNoneTrans(IInvocation invocation)
        {
            invocation.Proceed();
        }

        #endregion
    }
}
